package njust.csc.aeapi.service

import io.github.oshai.kotlinlogging.KotlinLogging
import njust.csc.aeapi.config.ApplicationVariables
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.ContentDisposition
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.stereotype.Service
import org.springframework.util.StreamUtils
import org.springframework.web.client.HttpClientErrorException
import org.springframework.web.client.RestTemplate
import java.net.URI
import java.nio.file.Path
import kotlin.io.path.Path
import kotlin.io.path.outputStream
private val logger = KotlinLogging.logger {}

/**
 * @Author ZhouHang
 * @Date 24/6/15 周六
 */
@Service
class HttpService @Autowired constructor(
    private val applicationVariables: ApplicationVariables,
) {
    /**
     * 将 url 下载到  applicationVariables.userInputDirPath 指定的位置
     * @param url 下载链接
     * @return 下载成功返回保存的路径，失败返回 null
     * */
    fun downloadFileToUserInput(url: String): Path? {
        val restTemplate = RestTemplate()
        var savePath: Path? = null
        try {
            restTemplate.execute(URI(url), HttpMethod.GET, null) { clientHttpResponse ->
                logger.info { "开始下载：${url}, code = ${clientHttpResponse.statusCode}" }
                val headers: HttpHeaders = clientHttpResponse.headers
                val contentDisposition: ContentDisposition = headers.contentDisposition
                var filename = contentDisposition.filename
                if (filename.isNullOrEmpty()) {
                    filename = url.split("/").last()
                }
                savePath = Path(applicationVariables.userInputDirPath).resolve(filename)
                try {
                    StreamUtils.copy(clientHttpResponse.body, savePath!!.outputStream())
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                logger.info { "$filename 下载到 $savePath" }
                true
            }
        } catch (e: HttpClientErrorException) {
            logger.error { "url: $url 获取失败" }
        } catch (e: IllegalArgumentException) {
            logger.error { "url: $url 获取失败" }
        }
        return savePath
    }
}